package cz.hanis.android.geography;

import cz.hanis.android.geography.models.Continent;
import cz.hanis.android.geography.models.Test;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class HighscoreHandler {

	private Context mContext;
	
	public HighscoreHandler(Context context) {
		mContext = context;
	}
	
	public int getHighScore(String testId, String continent, int testType) {
		SharedPreferences prefs = mContext.getSharedPreferences(
				PreferenciesTools.APP_PRIVATE_PREFERENCIES, Context.MODE_PRIVATE);				
		int highscore = prefs.getInt(getTestCode(testId, continent, testType), 0);						
		return highscore;
	}

	public int getHighScore(TestSpecification testSpec) {
		return getHighScore(testSpec.getTestId(), testSpec.getContinent(), testSpec.getTestTypeId());
	}

	public int getHighScoreAndSetIfGreater(String testId, String continent, int testType, int score) {
		SharedPreferences prefs = mContext.getSharedPreferences(
				PreferenciesTools.APP_PRIVATE_PREFERENCIES, Context.MODE_PRIVATE);				
		int highscore = prefs.getInt(getTestCode(testId, continent, testType), 0);
		if(highscore < score) {
			setHighScore(testId, continent, testType, score);
		}
		return highscore;
	}

	
	public void setHighScore(String testId, String continent, int testType, int score) {
		SharedPreferences prefs = mContext.getSharedPreferences(
				PreferenciesTools.APP_PRIVATE_PREFERENCIES, Context.MODE_PRIVATE);				
		Editor editor = prefs.edit();
		String code = getTestCode(testId, continent, testType);
		editor.putInt(code, score);
		editor.commit();		
	}
	
	public void removeAllHighscores() {
		for (int i = 0; i < 2; i++) {
			for(int j = 0; j < Continent.getNumberOfContinents(); j++) {
				for(Test test : GeographyApplication.getInstance().getTestManager().getTests()) {
					setHighScore(test.getId(), Continent.getIdByPosition(j), i, 0);
				}
			}
		}
	}
	
	private String getTestCode(String testId, String continent, int testType) {
		return testId + continent + testType;
	}	
	
	
	
}
